package com.dwms.service;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.dwms.cache.SellerCache;
import com.dwms.entity.QueryRequest;
import com.dwms.entity.Result;
import com.dwms.entity.api.request.ApiCommonRequest;
import com.dwms.entity.api.request.ApiOrderItemRequest;
import com.dwms.entity.api.request.ApiOrderRequest;
import com.dwms.entity.base.sellerKey.response.SellerKeyResponse;
import com.dwms.entity.common.CommonMessage;
import com.dwms.entity.common.MqRequest;
import com.dwms.enums.ApiMethodType;
import com.dwms.enums.MqGroup;
import com.dwms.enums.ResultCode;
import com.dwms.feign.MqFeignClient;
import com.dwms.feign.OrderFeignClient;
import com.dwms.feign.SellerKeyFeignClient;
import com.dwms.utils.AesEncryptUtil;
import com.dwms.utils.EmptyUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class GatewayService {

    private final MqFeignClient mqFeignClient;
    private final OrderFeignClient orderFeignClient;
    private final SellerKeyFeignClient sellerKeyFeignClient;

    /**
     * 处理业务逻辑
     * @param apiCommonRequest
     * @return
     */
    public Result handleApiBusiness(ApiCommonRequest apiCommonRequest) {
        Result result = checkParams(apiCommonRequest);
        if (result.isFailed()) {
            return result;
        }
        Result<ApiCommonRequest> signResult = checkSign(apiCommonRequest);
        if (signResult.isFailed()) {
            return signResult;
        }
        ApiMethodType apiMethodType = ApiMethodType.getTypeByV1Code(apiCommonRequest.getMethod());
        return switch (apiMethodType) {
            case ORDER_CREATE -> orderCreate(signResult.getData());
            case ORDER_STORAGE -> Result.success();
            case ORDER_CUSTOM -> Result.success();
            case ORDER_DELIVER -> Result.success();
            case ORDER_STATUS -> Result.success();
            case GOODS_STOCK -> Result.success();
            case LOGISTICS_TRACES -> Result.success();
            case LOGISTICS_WAYBILL -> Result.success();
            case LOGISTICS_CUSTOM -> Result.success();
        };
    }

    /**
     * 订单创建
     * @param apiCommonRequest
     * @return
     */
    private Result orderCreate(ApiCommonRequest apiCommonRequest) {
        if (null == apiCommonRequest || EmptyUtils.isEmpty(apiCommonRequest.getBizContent())) {
            return Result.failed("参数异常");
        }
        if (null == apiCommonRequest.getSellerKey()) {
            return Result.failed("参数appId不正确");
        }
        ApiOrderRequest apiOrderRequest = JSONObject.parseObject(apiCommonRequest.getBizContent(), ApiOrderRequest.class);
        Result bizResult = checkBizParams(apiOrderRequest);
        if (bizResult.isFailed()) {
            return bizResult;
        }
        apiOrderRequest.setSellerId(apiCommonRequest.getSellerKey().getId());
        apiOrderRequest.setNotifyUrl(apiCommonRequest.getNotifyUrl());
        return orderFeignClient.handelOrder(apiOrderRequest);
    }

    /**
     * 校验参数是否为空
     * @param apiCommonRequest
     * @return
     */
    private Result checkParams(ApiCommonRequest apiCommonRequest) {
        if (null == apiCommonRequest) {
            return Result.failed(ResultCode.PARAM_IS_BLANK);
        }
        if (EmptyUtils.isEmpty(apiCommonRequest.getAppId())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数appId不能为空");
        }
        if (EmptyUtils.isEmpty(apiCommonRequest.getMethod())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数method不能为空");
        }
        if (EmptyUtils.isEmpty(apiCommonRequest.getCharset())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数charset不能为空");
        }
        if (EmptyUtils.isEmpty(apiCommonRequest.getSignType())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数signType不能为空");
        }
        if (EmptyUtils.isEmpty(apiCommonRequest.getTimestamp())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数timestamp不能为空");
        }
        if (EmptyUtils.isEmpty(apiCommonRequest.getVersion())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数version不能为空");
        }
        if (EmptyUtils.isEmpty(apiCommonRequest.getBizContent())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数bizcontent不能为空");
        }
        return Result.success();
    }

    /**
     * 校验签名是否正确
     * @param apiCommonRequest
     * @return
     */
    private Result<ApiCommonRequest> checkSign(ApiCommonRequest apiCommonRequest) {
        Result<SellerKeyResponse> sellerKeyResult = this.sellerKeyFeignClient.findByAppKey(QueryRequest.build(apiCommonRequest.getAppId()));
        if (null == sellerKeyResult || null == sellerKeyResult.getData()) {
            return Result.failed(ResultCode.FAIL_BUSINESS, "appId不正确");
        }
        SellerKeyResponse sellerKey = sellerKeyResult.getData();
        if (null == sellerKey || EmptyUtils.isEmpty(sellerKey.getAppSecret())) {
            return Result.failed(ResultCode.FAIL_BUSINESS, "appId不正确");
        }
        if (!sellerKey.getEnabled()) {
            return Result.failed(ResultCode.ACCOUNT_FORBIDDEN, "appId已禁用");
        }
        apiCommonRequest.setSellerKey(sellerKey);
        String bizContent = AesEncryptUtil.aesCbcDecrypt(apiCommonRequest.getBizContent(), sellerKey.getAppSecret(), sellerKey.getSalt());
        if (EmptyUtils.isEmpty(bizContent)) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数bizcontent解密失败");
        }
        apiCommonRequest.setBizContent(bizContent);
        return Result.success(apiCommonRequest);
    }

    /**
     * 校验业务内容参数
     * @param apiOrderRequest
     * @return
     */
    private Result checkBizParams(ApiOrderRequest apiOrderRequest) {
        if (null == apiOrderRequest) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数bizcontent格式错误");
        }
        if (EmptyUtils.isEmpty(apiOrderRequest.getSellerOrderNo())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数sellerOrderNo不能为空" );
        }
        if (EmptyUtils.isNull(apiOrderRequest.getOrderGoodsType())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数orderGoodsType不能为空");
        }
        if (EmptyUtils.isNull(apiOrderRequest.getGoodsValue())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数goodsValue不能为空");
        }
        if (EmptyUtils.isNull(apiOrderRequest.getFreight())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数freight不能为空");
        }
        if (EmptyUtils.isNull(apiOrderRequest.getTaxTotal())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数taxTotal不能为空");
        }
        if (EmptyUtils.isNull(apiOrderRequest.getActuralPaid())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数acturalPaid不能为空");
        }
        if (EmptyUtils.isEmpty(apiOrderRequest.getBuyerRegNo())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数buyerRegNo不能为空");
        }
        if (EmptyUtils.isEmpty(apiOrderRequest.getBuyerName())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数buyerName不能为空");
        }
        if (EmptyUtils.isEmpty(apiOrderRequest.getBuyerIdNumber())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数buyerIdNumber不能为空");
        }
        if (EmptyUtils.isEmpty(apiOrderRequest.getConsignee())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数consignee不能为空");
        }
        if (EmptyUtils.isEmpty(apiOrderRequest.getConsigneeTelephone())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数consigneeTelephone不能为空");
        }
        if (EmptyUtils.isEmpty(apiOrderRequest.getConsigneeAddress())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数consigneeAddress不能为空");
        }
        if (EmptyUtils.isEmpty(apiOrderRequest.getAreaName())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数areaName不能为空");
        }
        if (EmptyUtils.isEmpty(apiOrderRequest.getOrderList())) {
            return Result.failed(ResultCode.PARAM_IS_BLANK, "参数orderList不能为空");
        }
        if (EmptyUtils.isNotEmpty(apiOrderRequest.getOrderList())) {
            List<ApiOrderItemRequest> apiOrderItemRequests = apiOrderRequest.getOrderList();
            if (EmptyUtils.isEmpty(apiOrderItemRequests)) {
                return Result.failed(ResultCode.PARAM_IS_BLANK, "参数orderList不能为空");
            }
            for (ApiOrderItemRequest apiOrderItemRequest : apiOrderItemRequests) {
                if (EmptyUtils.isNull(apiOrderItemRequest.getItemNum())) {
                    return Result.failed(ResultCode.PARAM_IS_BLANK, "参数itemNum不能为空");
                }
                if (EmptyUtils.isEmpty(apiOrderItemRequest.getItemNo())) {
                    return Result.failed(ResultCode.PARAM_IS_BLANK, "参数itemNo不能为空");
                }
                if (EmptyUtils.isEmpty(apiOrderItemRequest.getItemName())) {
                    return Result.failed(ResultCode.PARAM_IS_BLANK, "参数itemName不能为空");
                }
                if (EmptyUtils.isNull(apiOrderItemRequest.getQty())) {
                    return Result.failed(ResultCode.PARAM_IS_BLANK, "参数qty不能为空");
                }
                if (EmptyUtils.isEmpty(apiOrderItemRequest.getPrice())) {
                    return Result.failed(ResultCode.PARAM_IS_BLANK, "参数price不能为空");
                }
                if (EmptyUtils.isEmpty(apiOrderItemRequest.getTotalPrice())) {
                    return Result.failed(ResultCode.PARAM_IS_BLANK, "参数totalPrice不能为空");
                }
            }
        }
        if (EmptyUtils.isEmpty(apiOrderRequest.getPayTransactionId())) {
            if (EmptyUtils.isEmpty(apiOrderRequest.getEbpCode())) {
                return Result.failed(ResultCode.PARAM_IS_BLANK, "参数ebpCode不能为空");
            }
            if (EmptyUtils.isEmpty(apiOrderRequest.getEbpName())) {
                return Result.failed(ResultCode.PARAM_IS_BLANK, "参数ebpName不能为空");
            }
            if (EmptyUtils.isEmpty(apiOrderRequest.getCustomsOrderSn())) {
                return Result.failed(ResultCode.PARAM_IS_BLANK, "参数customsOrderSn不能为空");
            }
            if (EmptyUtils.isEmpty(apiOrderRequest.getPayCustomsCode())) {
                return Result.failed(ResultCode.PARAM_IS_BLANK, "参数payCustomsCode不能为空");
            }
            if (EmptyUtils.isEmpty(apiOrderRequest.getPayCustomsName())) {
                return Result.failed(ResultCode.PARAM_IS_BLANK, "参数payCustomsName不能为空");
            }
        }
        return Result.success();
    }
}
